import { NameSpace } from 'utils/index';
import { defaultPageSize } from 'utils/constants.js';
import { getCommitsList, getToken, getSearchData, getCommitsBuilds } from 'api';
import utils from 'utils';

export { updateCommitsPage } from '../../../actions/index';

const ns = NameSpace('projectCommits');

export const UPDATE_DATA = ns('UPDATE_DATA');
export const RECEIVE_BUILDS = ns('RECEIVE_BUILDS');
export const UPDATE_PAGE_INFO = ns('UPDATE_PAGE_INFO');

const {
  // pathResource,
  resourceSubject,
} = window.FORCE;

export function updateData(data) {
  return (dispatch) => {
    dispatch({
      type: UPDATE_DATA,
      data,
    });
  };
}

// 获取commits数据
export function getCommits(page, branch, cb) {
  const numberPage = Number(page);
  return (dispatch, getState) => {
    updateData({
      isLoading: true,
    })(dispatch);
    const state = getState().project.projectCommits;
    const { filterText } = state;
    let data = {
      ref_name: utils.getRevisionRef(
        branch || resourceSubject.revision,
        resourceSubject.revisionType,
      ),
      page: numberPage,
      search: filterText,
      show_signature: true,
      show_comments_count: true, // 出参带评论数量
    };

    if (resourceSubject.path) {
      data = { ...data, path: resourceSubject.path };
    }
    getCommitsList(data)
      .then((res) => {
        const newCommits = res.slice(1);
        const newTotal = newCommits.length === 20 ? numberPage * 10 + 1 : numberPage * 10;
        updateData({
          isLoading: false,
        })(dispatch);
        if (numberPage !== 1 && newCommits.length === 0) {
          if (cb && cb('nodata')) {
            // cb执行
          } else {
            updateData({
              commits: [...newCommits],
              currentPage: numberPage,
              total: newTotal,
            })(dispatch);
          }
          return;
        }
        updateData({
          commits: [...newCommits],
          currentPage: numberPage,
          total: newTotal,
        })(dispatch);
      })
      .catch((err) => {
        console.error(err);
      });
  };
}

// 不适用此处，下面方法是全局搜索，列表搜索只需要增加search字段即可
export function getData(page) {
  return (dispatch, getState) => {
    if (page == 1) {
      updateData({
        isLoading: true,
        commits: [],
      })(dispatch);
    }
    const state = getState().project.projectCommits;
    const { commits, filterText } = state;
    const data = {
      searchText: filterText,
      searchType: 'commits',
      sortBy: 'default|desc',
      currentPage: page,
      pageSize: defaultPageSize,
    };

    getToken()
      .then((result) => {
        data.privateToken = result.privateToken;
        return getSearchData(data);
      })
      .then((res) => {
        updateData({
          privateToken: data.privateToken,
          commits: [...commits, ...res.slice(1)],
          isLoading: false,
        })(dispatch);
      })
      .catch((err) => {
        updateData({
          isLoading: false,
        })(dispatch);
        console.error(err);
      });

    getCommitsList(data)
      .then((res) => {
        updateData({
          commits: [...commits, ...res.slice(1)],
          isLoading: false,
        })(dispatch);
      })
      .catch((err) => {
        console.error(err);
      });
  };
}

// 获取自动化扫描结果
export function getBuilds(commits) {
  return (dispatch) => {
    Promise.all(commits.map((commit) => getCommitsBuilds(commit.id)))
      .then((results) => {
        const checks = results.map((item) => {
          item.shift();
          return item;
        });

        dispatch({
          type: RECEIVE_BUILDS,
          data: checks,
        });
      })
      .catch((err) => {
        console.error(err);
      });
  };
}
